package com.lky.mall.product.service.impl;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.lky.mall.product.service.CategoryBrandRelationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lky.common.utils.PageUtils;
import com.lky.common.utils.Query;

import com.lky.mall.product.dao.CategoryDao;
import com.lky.mall.product.entity.CategoryEntity;
import com.lky.mall.product.service.CategoryService;


@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {

    @Autowired
    CategoryBrandRelationService categoryBrandRelationService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryEntity> page = this.page(
                new Query<CategoryEntity>().getPage(params),
                new QueryWrapper<CategoryEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public List<CategoryEntity> listWithTree() {
        List<CategoryEntity> entities = baseMapper.selectList(null);
        if (entities == null || entities.isEmpty()) {
            return Collections.emptyList();
        }
        //先1级分类提取出来 再递归他的子节点
        List<CategoryEntity> level1Menus = entities.stream().filter(categoryEntity ->
                categoryEntity.getParentCid() != null && categoryEntity.getParentCid() == 0
        ).map(menu -> {
            menu.setChildren(getChildrens(menu, entities));
            return menu;
        }).sorted((menu1, menu2) -> {
            Integer sort1 = menu1.getSort() == null ? 0 : menu1.getSort();
            Integer sort2 = menu2.getSort() == null ? 0 : menu2.getSort();
            return sort1 - sort2;
        }).collect(Collectors.toList());
        return entities;
    }

    @Override
    public void removeMenuByIds(List<Long> asList) {
        //todo 1、检查当前删除菜单，是否被别的菜单引用
        //逻辑删除
        baseMapper.deleteBatchIds(asList);
    }

    //[2,25,225]
    @Override
    public Long[] findCatelogPath(Long catelogId) {
        List<Long> paths = new ArrayList<>();
        findParentPath(catelogId,paths);
        //逆序转换，变成子节点在前
        Collections.reverse(paths);
        return paths.toArray(new Long[paths.size()]);
    }

    /*
    * 更新数据
    * */
    @Override
    public void updateCascade(CategoryEntity category) {
        //保证冗余字段的数据一致
        this.updateById(category);
        if (StringUtils.isNotBlank(category.getName())){
            //同步更新其他关联表中的字段
            categoryBrandRelationService.updateCategory(category.getCatId(),category.getName());
            //TODO 更新其他关联
        }
    }

    //递归
    private void findParentPath(Long catelogId, List<Long> paths) {
        paths.add(catelogId);
        CategoryEntity byId = this.getById(catelogId);
        if (byId.getParentCid() != 0){
            findParentPath(byId.getParentCid(),paths);
        }
    }

    private List<CategoryEntity> getChildrens(CategoryEntity root, List<CategoryEntity> all) {
        List<CategoryEntity> children = all.stream().filter(categoryEntity -> {
            return categoryEntity.getParentCid() == root.getCatId();
        }).map(categoryEntity -> {
            //找子菜单
            categoryEntity.setChildren(getChildrens(categoryEntity, all));
            return categoryEntity;
        }).sorted((menu1, menu2) -> {
            //菜单排序
            return (menu1.getSort() == null ? 0 : menu1.getSort()) - (menu2.getSort() == null ? 0 : menu2.getSort());
        }).collect(Collectors.toList());
        return children;
    }
}